#include "EventReceiver.h"
#include "CGameDevice.h"
#include "../log/Log.h"

	EventReceiver::EventReceiver(CGameDevice*gd){
		gamedevice=gd;
		rady=false;
		mouseLeftDown=false;
		refreshGameObject();
		gameObject=0;

	}

	void EventReceiver::addEvent(DYN_GUIEvent function,irr::gui::IGUIElement*caller,irr::gui::EGUI_EVENT_TYPE type){
		GUIEvent e;
		e.function=function;
		e.EventType=type;
		e.caller=caller;
		gui_events.push_back(e);
	}

	bool EventReceiver::OnEvent(const irr::SEvent& event){
		if (!gameObject){
			LOGE("game object is NULL");
			return false;
		}
		if(event.EventType == irr::EET_LOG_TEXT_EVENT){
				return gameObject->onLogEvent(event.LogEvent.Text,event.LogEvent.Level);
		}

		if (!rady)
			return true;

		if (!gamedevice->isRuning())
			return false;

		if (event.EventType==irr::EET_MOUSE_INPUT_EVENT){
			mouseNow.X=event.MouseInput.X;
			mouseNow.Y=event.MouseInput.Y;
			if (event.MouseInput.isLeftPressed()){
				if (!mouseLeftDown){
					mouseOld=mouseNow;
					mouseLeftDown=true;
				}

			}else
				mouseLeftDown=false;

			bool res=gameObject->onMouseEvent(event);
			mouseOld=mouseNow;
			return res;
		}

		if(event.EventType == irr::EET_KEY_INPUT_EVENT ){
			return gameObject->onKeyEvent(event);
		}



		if(event.EventType == irr::EET_JOYSTICK_INPUT_EVENT){
			return gameObject->onJoystickEvent(event);
		}

		if(event.EventType == irr::EET_GUI_EVENT){
			for (irr::u32 i=0;i<gui_events.size();i++){
				if (gui_events[i].caller==event.GUIEvent.Caller && gui_events[i].EventType==event.GUIEvent.EventType)
					return gui_events[i].function(event.GUIEvent.Caller,gui_events[i].EventType);
			}
			return gameObject->onGUIEvent(event);
		}

		return false;
	}

	irr::core::vector2di EventReceiver::getDeltaMouse(){
		return mouseNow-mouseOld;
	}

	void EventReceiver::refreshGameObject(){
		if (gamedevice==0){
			gameObject=0;
			rady=false;
			return;
		}
		gameObject=gamedevice->getGameObject();
		rady=gameObject!=0;
	}
